#!/usr/bin/env python
# @FileName :userapi.py
# @Time :2025/8/20 10:04
# @Author :chenjiajun
from base64 import decode

from flask_restful import Api,Resource
from flask import request

from form.user import Login, RegisterForm
from lib.auth import create_token, decode_jwt
from . import us_bp
from lib.resp import responseFunc
from model.user import User
import base64

api = Api(us_bp)

class create_user(Resource):




    def post(self):
        data = request.json
        form = RegisterForm(data = data)
        if form.validate():
            user_account = data['user_account']
            password = data['password']
            role = data['role']
            User.create_user(user_account, password, role)
            return responseFunc(message='注册成功',code = 20000)
        else:
            return responseFunc(message=f'注册失败{form.errors}', code = 0)




    def get(self,id = None):
        user = User.query.all()
        data = [dict(item) for item in user]
        return responseFunc(message='查询成功',code = 20000,data = data)


    def put(self):
        try:
            data = request.json
            userid = data['user_id']
            user_account = data['user_account']
            role = data['role']
            if 'password' in data:
                User.modify_user(userid, user_account, role, data['password'])
            else:
                User.modify_user(userid, user_account, role)
            return responseFunc(message='修改成功',code = 20000)
        except:
            return responseFunc(message='修改失败', code=0)


    def delete(self):
        try:
            data = request.json
            User.delete_user(data['user_id'])
            return responseFunc(message='删除成功',code = 20000)
        except:
            return responseFunc(message='删除失败', code = 0)

api.add_resource(create_user,'/user')
api.add_resource(create_user,'/user<id>',endpoint='create_user01')


class UserLogin(Resource):
    def post(self):
        try:
            data = request.json
            form = Login(data = data)
            user = form.validate()
            if user:
                token = create_token(user.user_id)
                return responseFunc(message='登陆成功',code = 20000,data = {"token" : token})
        except:
                return responseFunc(message='用户名或密码错误',code = 0)

    def get(self):
        token = request.args.get('token')
        decode = decode_jwt(token)
        user_id = int(decode['user_id'])
        user = User.query.get(user_id)
        return responseFunc(message='this is get',code = 20000,data = {"name":user.user_account,"avatar":"avatar"})
api.add_resource(UserLogin,'/UserLogin')